iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0

前言:

   函式,可以讓我們的code 看起來比較好懂,重複利用性也會提高。

大綱:

修飾符號  函式宣告關鍵字  函式名稱  (             函式參數              ) : 返回函式型
private   fun        iron30Day (afterDay: Int , totalDay: Int     ) :  Int 
        
        

函式是如何呼叫的

   class Day5Activity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_day5)

      callIthomeDaysLeft()
      printIthomeDaysLeft(5,)
      printIthomeDaysLeft(6,30)
    
      var ironDaysLeft:Int = returnIthomeDaysLeft(7,30)
      var ironDaysLeftDefault:Int = returnIthomeDaysLeft(7)
      var ironDaysLeft1:Int = returnIthomeDaysLeft1(7,30)
      println("return ironDaysLeft = "+ironDaysLeft)
      println("return ironDaysLeftDefault = "+ironDaysLeftDefault)
      println("return ironDaysLeft 1 Line = "+ironDaysLeft1)
      println(ironAfterDay(5))
   }

   //funtion unit  不用返回型式函式
   private fun callIthomeDaysLeft(){
    var totalDay =30
    var day =5
    println("Iron Day Left = "+ (totalDay-day))
   }

   //參數有預設值,不用返回型式函式
   private fun printIthomeDaysLeft(day:Int, totalDay:Int=30){
   println("Iron Day Left = "+ (totalDay-day))
   }

   //參數有預設值,返回 Int 型式函式
   private fun returnIthomeDaysLeft(day:Int, totalDay:Int=30) :Int{
     return totalDay - day
   }

   //one line function  單行表達式
   private fun returnIthomeDaysLeft1(day:Int, totalDay:Int=30) :Int = totalDay - day

   //lambda 表達式 
   private var ironAfterDay: (Int) -> String = { afterDay ->
    println("ironAfterDay = "+afterDay)
    "return ironAfterDay = "+afterDay
   }
   }

執行結果:
https://ithelp.ithome.com.tw/upload/images/20210910/20121643Tm48fOTfLF.png

參考:
https://kotlinlang.org/docs/functions.html
https://kotlinlang.org/docs/lambdas.html


上一篇
Kotlin Android 第4天,從 0 到 ML - 條件判斷
下一篇
Kotlin Android 第6天,從 0 到 ML - null safety ​
系列文
Kotlin Android 30天,從 0 到 ML (Machine Learning)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言